/****************************************************
	文件：Closure.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/11/5 15:1:38
	功能：
*****************************************************/

using System;
using UnityEngine;

namespace GCOptimizing
{
    public class Closure
    {
        /// <summary>
        /// 闭包，有匿名函数
        /// </summary>
        public void Test1()
        {
            int a = 1;
            Action action = () => { a = 2; };
            action.Invoke();
        }

        int a = 1;

        /// <summary>
        /// 匿名函数，无闭包
        /// </summary>
        public void Test2()
        {
            Action action = () => { a = 2; };
            action.Invoke();
        }

        /// <summary>
        /// 方法做参数，无闭包
        /// </summary>
        public void Test3()
        {
            Call(_Test3);
        }

        void _Test3()
        {
            a = 2;
        }

        /// <summary>
        /// 优化闭包，有匿名函数
        /// </summary>
        public void Test4()
        {
            int a = 0;
            Action<int> action = (p) => { p = 2; };
            action.Invoke(a);
        }

        static int b = 1;

        /// <summary>
        /// 优化闭包，有匿名函数
        /// </summary>
        public void Test5()
        {
            Action action = () => { b = 2; };
            action.Invoke();
        }

        Action mAction1;

        /// <summary>
        /// 优化匿名函数，无闭包
        /// </summary>
        public void Test6()
        {
            if (mAction1 == null)
            {
                mAction1 = () => { a = 2; };
            }

            mAction1.Invoke();
        }

        Action mAction2;

        /// <summary>
        /// 优化匿名函数，有闭包
        /// </summary>
        public void Test7()
        {
            int a = 0;
            if (mAction2 == null)
            {
                mAction2 = () => { a = 2; };
            }

            mAction2.Invoke();
        }

        Action<int> mAction3;

        /// <summary>
        /// 优化匿名函数，优化闭包
        /// </summary>
        public void Test8()
        {
            int a = 0;
            if (mAction3 == null)
            {
                mAction3 = (p) => { p = 2; };
            }

            mAction3.Invoke(a);
        }

        void Call(Action cb)
        {
            cb?.Invoke();
        }

        void Call(Action<int> cb, int p)
        {
            cb?.Invoke(p);
        }
    }
}